var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,tabElement = layui.element,
    id = getQueryVariable("id");

layui.use(['tableEdit'], function () {

    let tableEdit = layui.tableEdit;
    let layer = layui.layer;

    let productList = [];//产品
    let fileList = [];//附件

    var wjCatalogCode = "Blueprint";//文件编码

    let colourList = getdictionary(6,41);//颜色
    let unitList = getdictionary(6,42);//单位
    let logList = [{
        id: "1",
        operationtype: "text1",
        theoperator: "text2",
        operationdate: "text3",
        modifythecontent: "text4"
    }];

    //当前登录用户编码
    let loginUserCode = user.code;
    let loginUserName = user.name;

    let contentUploadFileList=[];//明细附件
    let blueprintContentList=[];//目录明细
    let detailIdTemp='';//明细临时id，用于保存附件
    let uploadTableType="attachmenttableid"; //使用哪个上传表格 contentUploadId：明细的上传表格 。默认attachmenttableid：图纸附件的上传表格

    let executorList = [];

    //供应商集合
    let supplierList=[];
    //临时id
    let tempId='';

    layer.ready(function () {
        /*//获取当前登陆用户名称
        $.ajax({
            url: "user/getAllUserNameAndCode",
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    executorList = res.data;
                    for (let i in res.data) {
                        $("#operator").append("<option value=\"" + res.data[i].code + "\">" + res.data[i].name + "</option>");
                    }

                    form.render('select');
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });*/

        if (id != "") {
            queryById();
        }else{
            $("#operator").val(loginUserCode);
            $("#operatorName").val(loginUserName);
        }
        //获取供应商信息
        $.ajax({
            url:"payment/getSupplierInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    supplierList = data.data;
                }
            }
        });

    })

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });
//表单初始值，修改时调用
    if (id != "") {
        $("#number").attr("readonly", true);
    } else {
        laydate.render({
            elem: '#createTime',
            type: 'date',
            value: new Date(),
        });
        $.ajax({
            type:'POST',
            url:'blueprint/getLatestOddNumber',
            dataType:"json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data != "") {
                        form.val("editor-form", {
                            "number": res.data,
                        })
                    }
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            },
            error: function (data) {
                layer.msg(data.msg, {icon: 5});
            }
        })
    }

//监听提交
    form.on('submit(form-element)', function (data) {
        var indexsl = 0;
        var detailInfoData = table.cache["detailInfoId"];
        $.each(detailInfoData, function (index, value) {
            if (typeof (detailInfoData[index]["contentName"]) == "undefined" || detailInfoData[index]["contentName"] == "") {
                layer.msg("明细信息第" + (index + 1) + "条产品目录不能为空");
                indexsl++;
                return false;
            }
            if (typeof (detailInfoData[index]["supplierName"]) == "undefined" || detailInfoData[index]["supplierName"] == "") {
                layer.msg("明细信息第" + (index + 1) + "条供应商名称不能为空");
                indexsl++;
                return false;
            }
        });
        if (indexsl == 0) {
            let reqData = data.field;
            reqData["blueprintContentList"] = detailInfoData;
            reqData["fileList"] = fileList;
            if (id == "") {
                insert(reqData,detailInfoData);
            } else {
                reqData.id = id;
                update(reqData);
            }
        }
        return false;
    });

    //明细附件提交
    form.on('submit(form-element2)', function (data) {
        let contentUploadData = table.cache["contentUploadId"];
        if (id=="" || detailIdTemp==""){
            layer.msg("请先保存主信息及明细信息!");
            return false;
        }
        contentUpload(contentUploadData);
    });
    //关闭
    form.on('submit(form-element3)', function () {
        setTimeout(function () {
            parent.detab("views/jsp/other/drawings.jsp");
            parent.intab("views/jsp/other/drawings.jsp", "图纸")
            parent.detab("views/jsp/other/tpl/newupdrawings.jsp?id=" + (id == ''?'':id),"添加，修改图纸");
        }, 1000);
    });



    //--目录信息
    table.render({
        elem: '#detailInfo',
        id: 'detailInfoId',
        data: blueprintContentList,
        toolbar: '#detailInfoToolbar',
        cols: [[
            {checkbox: true,title:'选择', width: 50},
            {field: 'contentName', title: '产品目录', width: 1000,event:'content'},
            {field: 'contentCode', hide:true},
            {field: 'contentPath', hide:true},
            {field: 'contentPid', hide:true},
            {field: 'contentId', hide:true},
            {field: 'supplierName', title: '供应商名称', width: 1000,  templet:'#supplierSelect'},
            {field: 'supplierCode', hide:true},
            {fixed: 'right', title: '操作', width: 80, align: 'center', toolbar: '#detailInfoEditor'},
        ]],
        page: true,
        limit:50,
        height: 380,
        done: function (res, curr, count) {

            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            for (let i in supplierList) {
                $('.supplierClass').append(new Option(supplierList[i].name, supplierList[i].code));
            }
            for (let i in res.data) {
                tempId = res.data[i].tempId;
                $("#supplier_" + tempId).val(res.data[i].supplierCode);
            }

            form.render('select');
        }
    });
    //切换选项卡时隐藏下面的表格
    tabElement.on('tab(tabElement)', function(){
        let layId=this.getAttribute('lay-id');
        if (layId!=1){
            uploadTableType="attachmenttableid";
            detailIdTemp='';
            $("#hidden").hide();
        }
    });

    form.on("select(supplierSelect_filter)", function(data){
        var elem = data.othis.parents("tr");
        var dataindex = elem.attr("data-index");
        var tabledata = table.cache["detailInfoId"];

        $.each(tabledata,function(index,value){
            if(value.LAY_TABLE_INDEX==dataindex){
                tabledata[index]["supplierCode"] = data.value;
                for(let i in supplierList){
                    if(data.value==supplierList[i].code){
                        tabledata[index]["supplierName"] = supplierList[i].name;
                    }

                }
            }
        });

    });


    form.on("select(colourSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["detailInfoId"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["colour"] = data.value;
            }
        });
    });
    form.on("select(unitSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["detailInfoId"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["unit"] = data.value;
            }
        });
    });

    table.on('tool(detailInfoTable)', function (obj) {
        let data = obj.data;

        if (obj.event === 'del') {
            layer.confirm('确认删除?', function (index) {
                let oldData =  table.cache["detailInfoId"];
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('detailInfoId',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });

        }else if (obj.event === 'content') {
            if(typeof(data.id)=="undefined" || data.id===""){
                layer.msg("请先保存主信息及明细信息");
                return false;
            }
            uploadTableType="contentUploadId";
            detailIdTemp=data.id;
            $("#hidden").show();

            $.ajax({
                type: 'get',
                url: "blueprint/selectBlueprintContentList?blueprintId="+id+"&detailId="+data.id,
                async: false,
                success: function (da) {
                    if (da.status == 200) {
                        contentUploadFileList = da.data ;
                    }
                },
                error: function (data) {
                    // layer.msg("获取失败!");
                }
            });

            table.render({
                elem: '#contentUpload'
                , data: contentUploadFileList
                , toolbar: '#attachmenttoolbar'
                , cols: [[
                    {checkbox: true, fixed: true},
                    {field: 'id', hide:true},
                    {field: 'blueprintId', hide:true},
                    {field: 'detailId', hide:true},
                    {field: 'fileOriginalName', title: '文件名称',event:'fileName'},
                    // {field: 'fileUrl', title: '文件路径'},
                    {field: 'fileType', title: '文件类型'},
                    {field: 'fileSize', title: '文件大小(KB)'},
                    {field: 'operationName', title: '操作员'},
                    {field: 'operationCode', hide:true},
                    {field: 'fileUploadTime', title: '上传时间',
                        templet: function(d) {
                            return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
                        }
                    },
                    {fixed: 'right', width: 150, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
                ]]
                , id: 'contentUploadId'
                , page: false
                , height: 300
            });

        }
    });

    table.on('toolbar(contentUploadTable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('contentUploadId', {}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });


    table.on('toolbar(detailInfoTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'importproducts':
                layer.open({
                    type: 2,
                    area: ['1500px', '800px'],
                    content: 'views/jsp/other/tpl/importproducts.jsp'
                });
                break;
            case 'del':
                var data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        var cbList = table.cache["detailInfoId"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("detailInfoId", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        }

    });


//---附件
    table.render({
        elem: '#attachment'
        , data: fileList
        , toolbar: '#attachmenttoolbar'
        , cellMinWidth: 220
        , cols: [[
            // {field: 'fileName', title: '文件名称', fixed: true,style:"overflow:hidden"},
            {field: 'wjName', title: '文件名称',style:"overflow:hidden", event:'fileName'},
            // {field: 'fileUrl', title: '文件路径',style:"overflow:hidden"},
            {field: 'fileType', title: '文件类型'},
            {field: 'fileSize', title: '文件大小(KB)'},
            {field: 'fileExecutor', title: '操作员'},
            {field: 'fileExecutorCode', hide:true},
            {field: 'fileUploadTime', title: '上传时间',
                templet: function(d) {
                    return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
                }
            },
            {fixed: 'right', width: 150, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'ftp/uploadFile'
        , field: 'uploadify'
        , accept: 'file'
        , data:{"fileType":"blueprint"}
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var newfilename = "";
                if (ispd(wjCatalogCode, file.name)) {
                    // newfilename = getFileName(file.name);
                    // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                    layer.confirm('已存在同名的文件，是否覆盖？', function (index) {
                        layer.close(index);
                    });
                }
                if (newfilename != "") {
                    var obj = {};
                    obj.code = index;
                    obj.name = newfilename;

                    if ( uploadTableType==="contentUploadId"){
                        contentUploadFileList.push(obj);
                    }else{
                        fileList.push(obj);
                    }

                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + newfilename + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        if ( uploadTableType==="contentUploadId"){
                            contentUploadFileList = fileListIns;
                        }else{
                            fileList = fileListIns;
                        }
                    });

                    $("#uploadlist").append(tr);
                }else{
                    var obj = {};
                    obj.code = index;
                    obj.name = file.name;
                    // fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        if ( uploadTableType==="contentUploadId"){
                            contentUploadFileList = fileListIns;
                        }else{
                            fileList = fileListIns;
                        }

                    });

                    $("#uploadlist").append(tr);
                }
            });
        }
        , done: function (res, index, upload) {
            var filename = "";
            for (var i = 0; i < uploadlist.length; i++) {
                if (uploadlist[i].code == index) {
                    filename = uploadlist[i].name;
                    break;
                }
            }
            if (res.data.length > 0) {
                var files = res.data;
                var filepaths = [];
                for (var i = 0; i < files.length; i++) {
                    var obj = {};
                    obj.fileName = files[i].fileName;
                    obj.ftpPath = files[i].ftpPath;
                    filepaths.push(obj);
                }
                if (savefile(filepaths, filename, wjCatalogCode)) {
                    let oldData;
                    if ( uploadTableType==="contentUploadId"){
                        oldData = contentUploadFileList;
                    }else{
                        oldData = fileList;
                    }

                    let newData = [];
                    let num = oldData.length+1;
                    for(let i in files){
                        let newFile = {};
                        // fileList[i].tempId = num;
                        newFile.fileName = files[i].fileName;
                        newFile.wjName = files[i].originalFileName;
                        newFile.fileOriginalName = files[i].originalFileName;
                        newFile.fileUrl = files[i].ftpPath;
                        newFile.fileSize = (this.files[index].size / 1024).toFixed(1);
                        newFile.fileType = this.files[index].type;
                        newFile.fileExecutor=loginUserName;
                        newFile.fileExecutorCode=loginUserName;
                        newFile.operationName=loginUserName;
                        newFile.operationCode=loginUserCode;
                        newData.push(newFile);
                        num++;
                    }
                    oldData.push.apply(oldData, newData);

                    if ( uploadTableType==="contentUploadId"){
                        contentUploadFileList = oldData;
                    }else{
                        fileList = oldData;
                    }

                    if ( uploadTableType==="contentUploadId"){
                        table.reload('contentUploadId', {data:contentUploadFileList});
                    }else if ( uploadTableType==="attachmenttableid"){
                        table.reload('attachmenttableid', {data:fileList});
                    }else{
                        table.reload('attachmenttableid', {data:fileList});
                    }

                }

                var tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            /* if (res.files.file) { //上传成功
                 var tr = $("#uploadlist").find('tr#upload-' + index)
                     , tds = tr.children();
                 tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                 tds.eq(3).html(''); //清空操作
                 return delete this.files[index]; //删除文件队列已经上传成功的文件
             }*/
            this.error(index, upload);
        }
        , error: function (index, upload) {
            let tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });
    table.on('tool(contentUploadTable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoad(data.fileUrl+'/'+data.fileName);
        } else if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                let oldData =  contentUploadFileList;
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('contentUploadId',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }else if (obj.event === 'fileName'){
            onLineFile(data.fileUrl+'/'+data.fileName);
        }
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoad(data.fileUrl+'/'+data.fileName);
        } else if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                let oldData =  fileList;
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('attachmenttableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }else if (obj.event === 'fileName'){
            onLineFile(data.fileUrl+'/'+data.fileName);
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: logList
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    function queryById() {
        $.ajax({
            async: false,
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:id,
            url: 'blueprint/selectByKey',
            success: function (da) {
                if (da.status == 200) {
                    form.val("editor-form", {
                        "number": da.data.number,
                        "createTime": da.data.createTime,
                        "operator": da.data.operator,
                        "operatorName": da.data.operatorName,
                        "remark": da.data.remark,
                        "boxStatus": da.data.boxStatus,
                    })

                    laydate.render({
                        elem: '#createTime',
                        type: 'date',
                        value: new Date(da.data.createTime),
                    });
                    blueprintContentList=da.data.blueprintContentList;
                    for(let j in blueprintContentList){
                        blueprintContentList[j]['tempId'] = blueprintContentList[j]["id"];
                    }
                    fileList = queryFileByBid(id);
                } else {
                    layer.msg("初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("初始化失败!");
            }
        });
    }

    //产品
    function queryProductByBid(bId) {
        let resList = [];
        $.ajax({
            type: 'POST',
            url: 'blueprint/selectProductByBid/' + bId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data != null) {
                        resList = res.data;
                        form.val("editor-form", {
                            "productNo": res.data.productNo,
                            "specNo": res.data.specNo,
                            "normExplain": res.data.normExplain,
                            "chineseName": res.data.chineseName,
                            "englishName": res.data.englishName,
                            "chineseDesc": res.data.chineseDesc,
                            "englishDesc": res.data.englishDesc,
                            "unit": res.data.unit,
                            "colour": res.data.colour,
                            "customerArticleNo": res.data.customerArticleNo,
                        })
                        for (let i = 0; i < resList.length; i++) {
                            resList[i].tempId = i;
                        }
                        form.render('select');
                    } else {
                        layer.msg(res.msg, {icon: 3});
                    }
                } else {
                    // layer.msg("产品初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("产品初始化失败!");
            }
        });
        return resList;
    }

    //附件
    function queryFileByBid(bId) {
        let resList = [];
        $.ajax({
            type: 'POST',
            url: 'blueprint/selectFileByBid/' + bId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data != null) {
                        resList = res.data;
                        form.val("editor-form", {
                            "wjName": res.data.wjName,
                            // "fileName": res.data.fileName,
                            "fileUrl": res.data.fileUrl,
                            "fileType": res.data.fileType,
                            "fileSize": res.data.fileSize,
                            "fileExecutor": res.data.fileExecutor,
                            "fileUploadTime": res.data.fileUploadTime,
                        })
                    } else {
                        layer.msg(res.msg, {icon: 3});
                    }
                } else {
                    // layer.msg("附件初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("附件初始化失败!");
            }
        });
        return resList;
    }

    //新增明细附件
    function contentUpload(contentUploadData){
        let req={}
        req.blueprintId=id;
        req.detailId=detailIdTemp;
        req.files=contentUploadData;

        $.ajax({
            type: 'POST',
            data: JSON.stringify(req),
            url: 'blueprint/contentUploadData',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function (da) {
                if (da.status == 200) {
                    layer.msg("保存附件成功", {icon: 6});
                } else {
                    layer.msg(da.msg);
                }
            },
            error: function (data) {
                layer.msg("添加失败!");
            }
        });
    }
    //新增图纸
    function insert(data,productCache) {
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'blueprint/add',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    let zhuId=da.data.zhuId;
                    id=zhuId;
                    let detailArray=da.data.map.detailArray;
                    for(let i in productCache){
                        for(let i in detailArray){
                            if (detailArray[i].tempId == productCache[i].tempId){
                                productCache[i].id = detailArray[i].id;
                            }
                        }
                    }
                    layer.msg("新增成功!");
                    table.reload('detailInfoId',{data : productCache});
                } else {
                    layer.msg(da.msg);
                }
            },
            error: function (data) {
                layer.msg("添加失败!");
            }
        });
    }

    function update(data) {
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'blueprint/update',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    tf = true;
                    layer.msg("修改成功!");
                } else {
                    layer.msg("修改失败!");
                }
            },
            error: function (data) {
                layer.msg("修改失败!");
            }
        });
        return tf;
    }

    function getColourName(code){
        for(let i in colourList){
            if(colourList[i].code == code){
                return colourList[i].name;
            }
        }
        return "";
    }

    function getUnitName(code){
        for(let i in unitList){
            if(unitList[i].code == code){
                return unitList[i].name;
            }
        }
        return "";
    }

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }


    //获取文件目录下所有的文件名
    function ispd(wjCatalogCode, filename) {
        /* fileNames=[];*/
        var cun = false;
        $.ajax({
            type: 'get',
            //  url : 'resource/getTree',
            data: {"wjCatalogCode": wjCatalogCode, "name": filename},
            url: 'wjinfo/ispd',
            dataType: "json",
            /*  contentType: 'application/json',*/
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data == 0 ? false : true;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
        // return obj;
    }

    function getFileName(filename) {
        /* fileNames=[];*/
        var cun = "";
        $.ajax({
            type: 'get',
            //  url : 'resource/getTree',
            data: {"filename": filename},
            url: 'wjinfo/getFileName',
            dataType: "json",
            /*  contentType: 'application/json',*/
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
        // return obj;
    }

    //判断文件名是否重复
    function iscf(filename) {
        var tf = false;
        for (var i = 0; i < fileNames.length; i++) {
            if (filename == fileNames[i]) {
                tf = true;
                break;
            }
        }
        return tf;
    }

    //保存上传的文件
    function savefile(filepaths, filename, wjCatalogCode) {
        var tf = false;
        $.ajax({
            type: 'post',
            data: {
                "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
                "name": JSON.stringify(filename)
            },
            url: 'wjinfo/savefile',
            dataType: "json",
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    tf = da.data == 0 ? false : true;
                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return tf;
    }

});


